package com.uziot.boot.mybatis.batch;

import com.uziot.boot.mybatis.domain.BucketArea;
import com.uziot.boot.mybatis.mapper.BucketAreaMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author shidt
 * @version V1.0
 * @className BatchInsertService
 * @date 2021-03-05 15:34:46
 * @description
 */

@Service
public class BatchInsertServiceImpl {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 批处理
     *
     * @param areaList 列表处理
     */
    @Transactional(rollbackFor = Exception.class)
    public void addBatch(List<BucketArea> areaList) {
        // 将模式设置为批量提交，自动提交开关设置为false
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        BucketAreaMapper mapper = session.getMapper(BucketAreaMapper.class);
        for (int i = 0; i < areaList.size(); i++) {
            mapper.insertSelective(areaList.get(i));
            // 每1000条提交一次防止内存溢出
            if (i % 1000 == 999) {
                session.commit();
                session.clearCache();
            }
        }
        session.commit();
        session.clearCache();
    }


}
